﻿using log4net;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NiuBeService
{
    class ProgramRunner
    {
        private readonly static ILog logger = LogManager.GetLogger(nameof(ProgramRunner));

        public ProgramRunner()
        {

        }

        public async Task StartAsync()
        {
            var pre = "###";
            var jobInfos = JsonConfig.Get<CronJob>("CronJob.json")?.JobInfos;
            //check json file
            if (jobInfos == null)
            {
                logger.Info($"{pre}get assemly error,please check JsonConfig/CronJob.json");
                logger.Info($"{pre}no job loaded");
                return;
            }

            //check samejobs
            var sameJobs = from j in jobInfos.Where(x => x.Enable == true)
                           group j by j.JobName into g
                           select new { c = g.Count(), j = g.Key };

            if (sameJobs.Where(x => x.c > 1).Any())
            {
                logger.Info($"{pre}exist same jobname:{string.Join(",", sameJobs.Where(x => x.c > 1).Select(x => x.j))},");
                logger.Info($"{pre}all job loaded fail!");
                return;
            }

            var loadLog = new StringBuilder();
            loadLog.AppendLine($"");

            var successful = 0;
            for (int i = 1; i <= jobInfos.Count; i++)
            {
                var jobInfo = jobInfos[i - 1];
                var type = AutofacHelper.GetAssemlyJobs(jobInfo.JobName);
                if (type != null)
                {
                    var cronDescription = jobInfo.Cron.CronDescription();

                    if (cronDescription != "#")
                    {
                        successful++;
                        await QuartzManager.AddJobAsync(type, jobInfo.Cron);
                        loadLog.AppendLine($"{pre}[{i}] load job successful,job name:{jobInfo.JobName},corn:{jobInfo.Cron}->[{cronDescription}]");
                    }
                    else
                    {
                        loadLog.AppendLine($"{pre}[{i}] load job error,corn error,job name:{jobInfo.JobName},corn:{jobInfo.Cron}");
                    }
                }
                else
                {
                    loadLog.AppendLine($"{pre}[{i}] load job error,no assemlyjob,job name :{jobInfo.JobName}");
                }
            }
            loadLog.AppendLine($"{pre}loaded all job,total/successful/error:{jobInfos.Count}/{successful}/{jobInfos.Count - successful}");

            logger.Info(loadLog);
        }

        public async Task StopAsync()
        {
            await QuartzManager.ShutdownAllAsync();
        }

        //public async Task ContinueAsync(HostControl hostControl)
        //{
        //    await QuartzManager.ResumeAllAsync();
        //}

        //public async Task Pause(HostControl hostControl)
        //{
        //    await QuartzManager.PauseAllAsync();
        //}
    }




}
